package com.pro.core.validator;

import com.baidu.unbiz.fluentvalidator.ValidationError;
import com.baidu.unbiz.fluentvalidator.Validator;
import com.baidu.unbiz.fluentvalidator.ValidatorContext;
import com.baidu.unbiz.fluentvalidator.ValidatorHandler;

import java.math.BigDecimal;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 校验金额格式
 */
public class MoneyValidator extends ValidatorHandler<Object> implements Validator<Object> {

	private String fieldName;

	public static String MAX_AMOUNT = "10000";

	public MoneyValidator(String fieldName) {
		this.fieldName = fieldName;
	}

	@Override
	public boolean validate(ValidatorContext context, Object money) {
		if (null == money || money.equals("") || money.equals("null")) {
			context.addError(ValidationError.create(String.format("%s不能为空！", fieldName))
	                .setErrorCode(-1)
	                .setField(fieldName)
	                .setInvalidValue(money));
			return false;
		}
		String moneyStr = (String) money;
		Pattern pattern = Pattern.compile("^(([1-9]{1}\\d*)|([0]{1}))(\\.(\\d){0,2})?$"); // 判断小数点后2位的数字的正则表达式
		Matcher match = pattern.matcher(moneyStr);
		if (match.matches()) {
			if (new BigDecimal(moneyStr).compareTo(new BigDecimal("0.01")) >= 0 && new BigDecimal(moneyStr).compareTo(new BigDecimal(MAX_AMOUNT)) <= 0) {
				return true;
			} else {
				context.addError(ValidationError.create(String.format("%s金额格式不正确，取值范围[0.01,100000000.00]。请检查后重试", fieldName))
						.setErrorCode(-1)
						.setField(fieldName)
						.setInvalidValue(money));
				return false;
			}

		} else {
			context.addError(ValidationError.create(String.format("%s金额格式不正确，取值范围[0.01,100000000.00]。请检查后重试", fieldName))
					.setErrorCode(-1)
					.setField(fieldName)
					.setInvalidValue(money));
			return false;
		}
	}
}
